const express = require('express');
const router = express.Router();
const { asyncHandle } = require('../getSendResult');
const { createTaskList, findTaskList, deleteTask, updateTask,doneTask } = require('../../services/taskList');
const moment = require('moment');


// 创建任务
router.post('/createTaskList', asyncHandle(
    async (req, res, next) => {
        const name = req.body.name;
        const description = req.body.description;
        const content = req.body.content;
        const completeTargetTime = req.body.completeTargetTime;
        const completeTime = req.body.completeTime;
        const isDone = req.body.isDone;
        return await createTaskList(
            name,
            description,
            content,
            completeTargetTime,
            completeTime,
            isDone,
            req.id
        );
    }
))

// 查询任务
router.get('/findTaskList', asyncHandle(
    async (req, res, next) => {
        const page = req.query.page || 1;
        const limit = req.query.limit || 10;
        return await findTaskList(page, limit, req.id);
    }
));

// 查询今日任务
router.get('/findTaskToday', asyncHandle(
    async (req, res, next) => {
        let result = await findTaskList(1, 100, req.id);
        return result.filter((item) => {
            return moment(item.creatiedTime).isSame(new Date(), 'day');
        });
    }
))


// 查询今日已完成任务
router.get('/findCompletedTaskToday', asyncHandle(
    async (req, res, next) => {
        let result = await findTaskList(1, 100, req.id);
        return result.filter((item) => {
            return moment(item.creatiedTime).isSame(new Date(), 'day') && item.isDone;
        });
    }
))

// 查询历史任务/今日以前的任务前十条，并排序
router.get('/findHistoryTask', asyncHandle(
    async (req, res, next) => {
        let result = await findTaskList(1, 100, req.id);
        result = result.filter((item) => {
            return moment(item.creatiedTime).isBefore(new Date(), 'day');
        })
        result.sort((a, b) => {
            return moment(a.creatiedTime).isBefore(b.creatiedTime, 'second');
        }).reverse();
        return result.splice(0, 10);
    }
))

// 根据Id删除任务
router.get('/deleteTask', asyncHandle(
    async (req, res, next) => {
        const id = req.query.id;
        return await deleteTask(id);
    }
))

// 根据id更新任务
router.post('/updateTask', asyncHandle(
    async (req, res, next) => {
        const id = req.body.id;
        const name = req.body.name;
        const description = req.body.description;
        const content = req.body.content;
        const completeTargetTime = req.body.completeTargetTime;
        return await updateTask(id, name, description, content, completeTargetTime);
    }
))

// 根据id完成任务
router.get('/doneTask',asyncHandle(
    async (req,res,next)=>{
        console.log(req.query.id);
        return await doneTask(req.query.id);
    }
))

module.exports = router;